package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.common.ResultResponse;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理
 * 要求：
 * 1、使用REST full： 所有请求都必须要 POST http://localhost:8080/users
 * 2、返回的数据都是json数据  @ResponseBody
 * 3、将返回的数据标准化（将返回的数据都统一）: 为了前端更高效，返回结果都统一在一个对象（ResultResponse）中返回
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/{id}")
    public ResultResponse<User> queryUser(@PathVariable Long id) {
        User user = userService.queryUser(id);
        return ResultResponse.SUCCESS(user);
    }

    @GetMapping
    public ResultResponse<PageInfo> queryPage(String name, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo pageInfo = userService.queryPage(name, pageNum, pageSize);
        return ResultResponse.SUCCESS(pageInfo);
    }

    @PostMapping
    public ResultResponse<String> saveUser(@RequestBody User user) {
        //调用service层完成插入到数据
        userService.insertUser(user);
        return ResultResponse.SUCCESS("新增成功");
    }

    @DeleteMapping("/{id}")
    public ResultResponse<String> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResultResponse.SUCCESS("删除成功");
    }

    @PutMapping
    public ResultResponse<String> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return ResultResponse.SUCCESS("修改成功");
    }

}
